<!--
Date: 2025-08-13
Copyright (c) 2025 CAX Conversion Project
-->
<template>
  <div class="p-2 arithmetic_main">
    <div class="mb-[10px]">
      <el-card shadow="hover">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" size="small" label-width="80">
          <el-form-item label="材料名称" prop="materialName">
            <el-input style="width: 160px;" v-model="queryParams.materialName" placeholder="请输入材料名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="材料卡编号" prop="materialNumber">
            <el-input style="width: 160px;" v-model="queryParams.materialNumber" placeholder="请输入材料卡编号" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item style="padding-left: 80px">
            <el-button size="small" type="primary" icon="search" @click="handleQuery">搜索</el-button>
            <el-button size="small" icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button size="small" v-hasPermi="['system:oss:upload']" type="primary" plain icon="Plus" @click="addMaterial">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button size="small" v-hasPermi="['system:oss:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">
              删除
            </el-button>
          </el-col> -->
        </el-row>
      </template>

      <div v-if="tableShow" id="myElement" style="width: 100%;height: calc(100vh - 138px)"></div>
    </el-card>
    <!-- 添加或修改OSS对象存储对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="600px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="150px" inline size="small">
        <template v-for="item in columns">
          <el-form-item v-if="item.field !== 'operation'" :key="item.title" :label="item.field" :prop="item.field">
            <el-input v-model.trim="form[item.field]" placeholder="请输入" clearable />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button size="small" @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, reactive } from 'vue';
import * as VTable from '@visactor/vtable';
import VChart from '@visactor/vchart';
VTable.register.chartModule('vchart', VChart);
import { 
  getCompositeMaterialList, 
  addCompositeMaterial, 
  updateCompositeMaterial, 
  deleteCompositeMaterial, 
  getMetalMaterialList,
  addMetalMaterial,
  updateMetalMaterial,
  deleteMetalMaterial
} from '@/api/lyingWarehouse';
import { pageCompositeColumns, pageMetalColumns } from './pageConfig.js';
const { proxy } = getCurrentInstance();

let records = ref([]);
const tableShow = ref(true)
const props = defineProps({
  type: {
    type: String,
    default: ''
  }
})
const columns = ref(props.type == 'composite' ? pageCompositeColumns : pageMetalColumns)
!columns.value.some(item => item.field == 'operation') && columns.value.push({
  field: 'operation',
  title: '操作',
  width: 100,
  headerStyle:{
    fontWeight: 500,
    textAlign:'center'
  },
  icon: [
    {
      name: 'edit',
      type: 'svg',
      marginLeft: 10,
      positionType: VTable.TYPES.IconPosition.left,
      width: 16,
      height: 16,
      title: '编辑',
      svg: 'https://lf9-dp-fe-cms-tos.byteorg.com/obj/bit-cloud/VTable/edit.svg',
      tooltip: {
        style: { arrowMark: true },
        // 气泡框，按钮的的解释信息
        title: '编辑',
        placement: VTable.TYPES.Placement.right
      }
    },
    {
      name: 'delete',
      type: 'svg',
      marginLeft: 10,
      positionType: VTable.TYPES.IconPosition.left,
      width: 16,
      height: 16,
      title: '删除',
      svg: 'https://lf9-dp-fe-cms-tos.byteorg.com/obj/bit-cloud/VTable/delete.svg',
      tooltip: {
        style: { arrowMark: true },
        // 气泡框，按钮的的解释信息
        title: '删除',
        placement: VTable.TYPES.Placement.right
      }
    }
  ]
})
const loading = ref(false)
const dialog = reactive({
  visible: false,
  title: "新增"
})
const form = ref({});
const queryParams = reactive({
  pageNum: 1,
  pageSize: 9999,
  materialName: '',
  materialNumber: ''
});
const handleQuery = () => {
  getListdata();
}
const resetQuery = () => {
  queryParams.materialName = ''
  queryParams.materialNumber = ''
  getListdata();
}
// const { queryParams, form, rules } = toRefs(data);
const addMaterial = () => {
  form.value = {};
  dialog.title = "新增"
  dialog.visible = true;
}
/** 查询算例库列表 */
const getListdata = async () => {
  loading.value = false;
  tableShow.value = false;
  const response = props.type == 'metal' ? await getMetalMaterialList(queryParams) : await getCompositeMaterialList(queryParams);
  records.value = response.rows;
  loading.value = false;
  const option = {
    records:records.value,
    columns: columns.value,
    transpose: false,
    defaultColWidth: 100,
    defaultRowHeight: 50,
    defaultHeaderRowHeight: 50,
  };
  tableShow.value = true;
  nextTick(() => {
    const tableInstance = new VTable.ListTable(document.querySelector('#myElement'), option);  
    window['tableInstance'] = tableInstance;  
    tableInstance.on('click_cell', async args => {
      const { col, row, targetIcon, originData } = args;
      if (targetIcon) {
        if (targetIcon.name === 'edit') {
          let formItems = props.type == 'composite' ? pageCompositeColumns : pageMetalColumns
          formItems.forEach(item => {
            if (item.field !== 'operation') {
              form.value[item.field] = originData[item.field];
            }
          })
          form.value.id = originData.id;
          dialog.visible = true;
          dialog.title = "编辑"
        } else if (targetIcon.name === 'delete') {
          handleDelete(originData)
        }
      }
    });
  })
};

/** 取消按钮 */
function cancel() {
  dialog.visible = false;
}

/** 提交按钮 */
const submitForm = async () => {
  loading.value = false;
  console.log('form.id', form.value.id)
  if (form.value.id) {
    props.type == 'metal' 
      ? await updateMetalMaterial(form.value).finally(() => (loading.value = false)) 
      : await updateCompositeMaterial(form.value).finally(() => (loading.value = false));
  } else {
    props.type == 'metal' 
      ? await addMetalMaterial(form.value).finally(() => (loading.value = false)) 
      : await addCompositeMaterial(form.value).finally(() => (loading.value = false));
  }
  await getListdata();
  proxy?.$modal.msgSuccess(form.value.id ? '编辑成功' : '新增成功');
  dialog.visible = false;
};
/** 删除按钮操作 */
const handleDelete = async (row) => {
  const ids = row?.id || ids.value;
  await proxy?.$modal.confirm(row?.id ? '是否确认删除材料名称为"' + row?.materialName + '"的数据项?' : '是否确认删除当前所选全部数据项?');
  loading.value = true;
  props.type == 'metal' 
  ? await deleteMetalMaterial(ids).finally(() => (loading.value = false))
  : await deleteCompositeMaterial(ids).finally(() => (loading.value = false));
  await getListdata();
  proxy?.$modal.msgSuccess('删除成功');
};

onMounted(() => {
  getListdata();
});
</script>
<style lang="scss" scoped>
.arithmetic_main{
  height: calc(100vh - 84px);
  overflow: auto;
}
.pagenation {
  display: flex;
  justify-content: end;
  margin-top: 10px;
}
:deep(.el-upload) {
  display: block;
}
.full-screen {
  overflow-y: auto;
}
</style>
